/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cw.server;

import java.io.BufferedReader;
import java.io.FileReader;
import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Vinh_Dragon
 */
public class ServerConfig {

    private static String serverAdd;
    private static String port;
    public static String serverID;

    public void ServerConfig() {
    }

    /**
     * getRMIPath
     * @return "rmi://" + serverAdd + ":" + port + "/FileServer";
     */
    public String getRMIPath() {
        try {
            try {
                BufferedReader in = new BufferedReader(new FileReader("C:\\CrossWordsConfig.txt"));
                String str;
                while ((str = in.readLine()) != null) {
                    serverAdd = str;
                    System.out.println(serverAdd);
                    port = in.readLine();
                    System.out.println(port);
                }
                in.close();

                if (serverAdd.trim().equals("") || port.trim().equals("")) {
                    serverAdd = (InetAddress.getLocalHost()).getHostAddress().toString();
                    port = "1200";
                }
            } catch (Exception e) {
                serverAdd = (InetAddress.getLocalHost()).getHostAddress().toString();
                port = "1200";
                Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, e);
            }

            serverID = "rmi://" + serverAdd + ":" + port + "/FileServer";

        } catch (Exception e) {
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, e);
        }
        return serverID;
    }

    /**
     * Setup to connecting to server
     * @return
     * @throws RemoteException
     */
    public ServerInterface Setup() throws RemoteException {
        ServerInterface stub = null;
        try {
            stub = (ServerInterface) Naming.lookup(getRMIPath());
            System.out.println("Conneted to server");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Cannot connect to server....Let review ServerIP and Port");
            System.exit(0);
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, e);
        }
        return stub;
    }

    public static void main(String[] args) {
        ServerConfig sc = new ServerConfig();//Create instance of ServerConfig
        try {
            ServerInterface stub = sc.Setup(); //get Methods from Server Side;
        } catch (RemoteException ex) {
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
